<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 调度中心
 * @author Administrator
 *
 */
class DispatchCenter extends MY_Controller {

	/**
	 * @var DlnUserModel
	 */
	public  $mMember = null;
	
	/**
	 * @var DlnOrderModel
	 */
	public  $mOrder = null;
	
	public function __construct(){
		parent::__construct();	
		$this->loadModel('DlnUserModel', 'mMember', 'deliveryman');
		$this->loadModel('DlnOrderModel', 'mOrder', 'deliveryman');
	}
	
	/**
	 * 首页
	 */
	public function index(){
		$this->loadModel('AdmSettingModel', 'mSett', 'admin');
		
		$tA = $this->mUser->getCountyIds($this->userId, true, 2, true);
		
		$data = [
				'status' => $this->mOrder->status(),
				'type' => $this->mOrder->type(),
				'ak' => $this->mSett->get('map_key'),
				'city' => ($tA ? $tA[0]['province'].$tA[0]['city'].$tA[0]['county'] : '')
		];
		$this->view('deliveryman/dispatchCenter/home', $data,'datatable,datepicker,validation');
	}

	/**
     * 消费记录
     */
	public function getList(){
		
		$dateFrom = get('date_from');
		$dateTo = get('date_to');
		$code = trim(get('code'));
		$sendUser = trim(get('send_user'));
		$sendMobile = trim(get('send_mobile'));
		$sendToUser = trim(get('send_to_user'));
		$sendToMobile = trim(get('send_to_mobile'));
		$sendAddress = trim(get('send_address'));
		$sendToAddress = trim(get('send_to_address'));
		$deliveryman = trim(get('deliveryman'));
		$deliverymanMobile = trim(get('deliveryman_mobile'));
		$status = (int)get('status');
		$type = (int)get('type');
		$longitude = get('longitude');
		if( ! $longitude) $longitude = 0;
		$latitude = get('latitude');
		if( ! $latitude) $latitude = 0;
		
		$select = '(ACOS(SIN(('.$latitude.' * 3.1415) / 180 )
						*SIN((o.latitude * 3.1415) / 180 ) + COS(('
				.$latitude.' * 3.1415) / 180 ) * COS((o.latitude * 3.1415) / 180 ) * COS(('
						.$longitude.' * 3.1415) / 180 - (o.longitude * 3.1415) / 180 ) ) * 6380 )';
		
	    $select2 = '(ACOS(SIN(('.$latitude.' * 3.1415) / 180 )
						*SIN((u.latitude * 3.1415) / 180 ) + COS(('
								.$latitude.' * 3.1415) / 180 ) * COS((u.latitude * 3.1415) / 180 ) * COS(('
										.$longitude.' * 3.1415) / 180 - (u.longitude * 3.1415) / 180 ) ) * 6380 )';
		
		$this->db->select('`o`.`id`, `o`.`type`, `o`.`code`, `o`.`longitude`, `o`.`latitude`, `o`.`send_user`,
		if(o.status > 2, '.$select2.', '.$select.') as distance,ro.deliveryman_id,
		`o`.`send_address`, `o`.`send_mobile`, `o`.`send_to_user`, `o`.`send_to_address`, `o`.`send_to_longitude`,
		`o`.`send_to_latitude`, `o`.`distance` as `send_distance`, `o`.`send_to_mobile`, `o`.`status`, `o`.`addtime`
		,expect_arrive_time,u.name,u.mobile,o.income,u.longitude as u_longitude,u.latitude as u_latitude,o.rob_expect_time');
		$this->mOrder->setCountyIdWhere($this->countyItem, [2,3]);
				 
				 
		$dateFrom = strtotime(date('Y-m-d'));
		if($dateFrom){
			$this->db->where('o.addtime >=', $dateFrom);
		}
		
		if($code){
			$this->db->where('o.code', $code);
		}
		
		if($status){
			$this->db->where('o.status', $status);
		}
		
		if($sendUser){
			$this->db->like('o.send_user', $sendUser);
		}
		
		if($sendMobile){
			$this->db->where('o.send_mobile', $sendMobile);
		}
		
		if($sendToUser){
			$this->db->like('o.send_to_user', $sendToUser);
		}
		
		if($sendToMobile){
			$this->db->where('o.send_to_mobile', $sendToMobile);
		}
		
		if($sendAddress){
			$this->db->like('o.send_address', $sendAddress);
		}
		
		if($sendToAddress){
			$this->db->like('o.send_to_address', $sendToAddress);
		}
		
		if($type){
			$this->db->where('o.type', $type);
		}
		
		if($deliveryman){
			$this->db->where('(u.name like \'%'.$deliveryman.'%\' or u.mobile = \''.$deliveryman.'\')');
		}
			
		$data = $this->mMember->pagination($this->mOrder->tbOrder.' o', null, 'o.id');
        foreach ($data['data'] as $k => $v){
        	
        	$v['distance'] = $v['distance'] > 1
        	? round($v['distance'], 2).'km' : ceil($v['distance'] * 1000).'m';
        	
        	if($v['send_distance'] > 1000){
        		$v['send_distance'] = ($v['send_distance'] / 1000).'km';
        	}else{
        		$v['send_distance'] = $v['send_distance'].'m';
        	}
        	
        	$time = time();
        	$tI = ceil((time() - ($v['status'] == 1 ? $v['rob_expect_time'] : $v['expect_arrive_time'])) / 60);
        	$show  = '';
        	$class = '';
        	if(abs($tI) < 60){
        		$show = abs($tI).'分';
        	}elseif(abs($tI) > 60){
        		$e = abs($tI) % 60;
        		$show = floor(abs($tI) / 60).'时';
        		if($e > 0){
        			$show .= $e.'分';
        		}
        	}
        	
        	if($tI > 0){
        		$show = '超时'.$show;
        		$class = 'red';
        	}else{
        		$show = $show.'后超时';
        	}
            $tS = '<span class="hide longitude">'.($v['status'] > 2 ? $v['u_longitude'] : $v['longitude']).'</span>
            		<span class="hide latitude">'.($v['status'] > 2 ? $v['u_latitude'] : $v['latitude'] ).'</span>
            		<span class="hide order">'.json_encode($v).'</span>';
            $data['aaData'][$k][] = '<span class="'.$class.'">'.$v['code'].'</span>'.$tS.$this->mOrder->status($v['status'], true);
            $data['aaData'][$k][] = '<span class="'.$class.'">'.($v['mobile'] ? $v['name'].'<br/><span>'.$v['mobile'].'</span>' : '').'</span>';
            $data['aaData'][$k][] = '<span class="'.$class.'">'.$v['income'].'</span>';
            $data['aaData'][$k][] = '<span class="'.$class.'">'.$this->mOrder->type($v['type']).'</span>';
            $data['aaData'][$k][] = '<span class="'.$class.'">'.$show.'</span>';
            $btnConfig = array(
            		array(
            				'label' => '详情',
            				'icon' => '<i class="fa fa-eye"></i>',
            				'attr' => array(
            						'href' => getUrl('deliveryman/order/details?id='.$v['id']),
            						'class' => 'btn btn-xs btn-default',
            						'target' => '_bank'
            				),
            				'tag' => 'a',
            		),
            );
            
            $data['aaData'][$k][] = adminCreateBtn($btnConfig);
        }
        unset($data['data']);
        echo json_encode($data);
    }
    
    /**
     * 获取所有的配送员
     */
    public function getCourier(){
    
    	$longitude = get('longitude');
    	if( ! $longitude) $longitude = 0;
    	$latitude = get('latitude');
    	if( ! $latitude) $latitude = 0;
    	
    	$select = '(ACOS(SIN(('.$latitude.' * 3.1415) / 180 )
						*SIN((latitude * 3.1415) / 180 ) + COS(('
    			.$latitude.' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) * COS(('
    					.$longitude.' * 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380 )';
    	
    	$this->db->select('id,portrait,name,mobile,'.$select.'  as distance,longitude,latitude')
    			 ->where('type', 2)
    			 ->where('status', 2)
    			 ->where('work_status', 2)
    			 ->where_in('county_id', $this->countyItem)
    			 ->having('distance <', 4)
    			 ->limit(100);
    	
    	$data = $this->mMember->getAll($this->mMember->tbUser);
    	foreach ($data as $k => $v){
    		$data[$k]['portrait'] = getImage($v['portrait'], 'xs');
    		$data[$k]['distance'] = $v['distance'] > 1
    		? round($v['distance'], 2).'km' : ceil($v['distance'] * 1000).'m';
    	}
    	
    	
    	$this->ajaxReturn(1, '', $data);
    }
    
    /**
     * 分配订单
     */
    public function allot(){
    	
    	//表单验证
    	$vConf = array(
    			array('id', '订单id', 'required|numeric'),
    			array('deliveryman_id', '运送人', 'required|numeric'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$id = post('id');
    	$deliverymanId = post('deliveryman_id');
    	$this->db->select('o.status,o.rob_expect_time,o.expect_arrive_time,o.addtime')
    			  ->where('o.id', $id);
    	$this->mOrder->setCountyIdWhere($this->countyItem, [2,3]);
    	$data = $this->mOrder->getOne($this->mOrder->tbOrder.' o');
    	if( ! $data){
    		$this->appReturn(0, '运单不存在');
    	}
    	
    	$this->db->select('order_total')
    			 ->where(['status' => 2, 'id' => $deliverymanId, 'type' => 2])
    			 ->where_in('county_id', $this->countyItem);
    	$deliveryman = $this->mMember->getOne($this->mMember->tbUser);
    	if( ! $deliveryman){
    		$this->ajaxReturn(0, '配送员不存在，或以停用');	
    	}
    	
    	if($data['status'] == 5){
    		$this->appReturn(0, '运单已取消');
    	}
    	
    	if($data['status'] == 4){
    		$this->appReturn(0, '运单已经送达');
    	}
    	
    	$this->db->trans_begin();
    	if($data['status'] == 1){
	    	$dbData = [
	    			'deliveryman_id' => $deliverymanId,
	    			'order_id' => $id,
	    			'addtime' => time()
	    	];
	    	
	    	if( ! $this->mOrder->insert($this->mOrder->tbRelationOrder, $dbData)){
	    		$this->db->trans_rollback();
	    		$this->appReturn(0, '保存失败');
	    	}
	    	
	    	$time = $data['expect_arrive_time'] - $data['addtime'] + time();
	    	if( ! $this->mOrder->update($this->mOrder->tbOrder, ['status' => 2,
	    			'order_month' => date('Ymd'),'expect_arrive_time' => $time])){
	    			$this->db->trans_rollback();
	    			$this->appReturn(0, '保存失败');
	    	}
    	}else{
    		$this->db->select('deliveryman_id')
    				 ->where('order_id', $id);
    		$info = $this->mOrder->getOne($this->mOrder->tbRelationOrder);
    		if( ! $info){
    			$this->db->trans_rollback();
    			$this->ajaxReturn(0, '数据错误');
    		}
    		if($deliverymanId == $info['deliveryman_id']){
    			$this->db->trans_commit();
    			$this->appReturn(1, '保存成功');
    		}
    		
    		$dbData = [
    				'deliveryman_id' => $deliverymanId,
    		];
    		$this->db->where('order_id', $id);
    		if( ! $this->mOrder->update($this->mOrder->tbRelationOrder, $dbData)){
    			$this->db->trans_rollback();
    			$this->appReturn(0, '保存失败');
    		}
    		
    		
    		$this->db->select('order_total')
    				 ->where('id', $info['deliveryman_id']);
    		$user = $this->mMember->getOne($this->mMember->tbUser);
    		if( ! $user){
    			$this->db->trans_rollback();
    			$this->ajaxReturn(0, '数据错误');
    		}
    		$total = $user['order_total'] - 1;
    		$total = $total < 0 ? 0 : $total;
    		$dbData = ['order_total' => $total];
    		
    		$this->db->where('id', $info['deliveryman_id']);
    		if( ! $this->mMember->update($this->mMember->tbUser, $dbData)){
    			$this->db->trans_rollback();
    			$this->ajaxReturn(0, '数据错误');
    		}
    	}
    	
    	$this->db->where('id', $deliverymanId);
    	if( ! $this->mMember->update($this->mMember->tbUser, 
    			['order_total' => (int)$deliveryman['order_total'] + 1])){
    		$this->db->trans_rollback();
    		$this->appReturn(0, '保存失败');
    	}
    	
    	$this->db->trans_commit();
    	$this->appReturn(1, '保存成功');
    }
    
    /**
     * 获取统计数据
     */
    public function getStatistics(){

    	$this->db->where(['status' => 2, 'work_status' => 2])
    			 ->where_in('county_id', $this->countyItem);
    	$user = $this->mMember->count($this->mMember->tbUser);
    	$time = strtotime(date('Y-m-d'));
    	
    	$status5 = $this->mOrder->getTodayCount($this->countyItem, 0);
    	$status1 = $this->mOrder->getTodayCount($this->countyItem, 1);
    	$status2 = $this->mOrder->getTodayCount($this->countyItem, 2);
    	$status3 = $this->mOrder->getTodayCount($this->countyItem, 3);
    	$data = [
    				'user' => $user,
    				'status1' => $status1,
    				'status2' => $status2,
    				'status3' => $status3,
    				'status5' => $status5
    	];
    	$this->ajaxReturn(1, '', $data);
    }
}
